﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.Sql;

using System.DirectoryServices;


public partial class Login : System.Web.UI.Page
{
    ILE_Config ileConfig = new ILE_Config();
    ILE_Global ileGlobal = new ILE_Global();
    UsersBLL usersLogic = new UsersBLL();
    StatisticsBLL statsLogic = new StatisticsBLL();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            FocusRightControl();
           
            // Check if Login Failure is going on.
            if (statsLogic.IsLoginFailureGoingOn(Request.UserHostAddress.ToString(), Request.Browser.Browser.ToString() + " " + Request.Browser.Version.ToString()) == true)
            {
                // Check Browser
                if (Request.Browser.Browser.ToString() == "IE")
                {
                    ((LinkButton)Institut_Login.FindControl("lnkbtnLoginProblemHelp")).PostBackUrl = "Help.aspx#IETrouble";
                    Institut_Login.FindControl("lnkbtnLoginProblemHelp").Visible = true;
                }
                else
                {
                    ((LinkButton)Institut_Login.FindControl("lnkbtnLoginProblemHelp")).PostBackUrl = "Help.aspx#OtherTrouble";
                    Institut_Login.FindControl("lnkbtnLoginProblemHelp").Visible = true;
                }
            }
            else
            {
                Institut_Login.FindControl("lnkbtnLoginProblemHelp").Visible = false;
            }
        }

        if (User.Identity.IsAuthenticated == true)
        {
            Response.Write("<script>alert('You are already logged in'); window.location.href='Default.aspx';</script>");
        }
        else
        {
            try
            {
                int TabIndex = -1;
                TabIndex = Convert.ToInt32(Request.QueryString["TabIndex"].ToString());
                TabContainerLogin.ActiveTabIndex = TabIndex;
                NonInstitut_Login.Focus();
            }
            catch
            {
            }

            if (Convert.ToInt32(HttpContext.Current.Session["AntiHacking"]) >= 5)
            {
                if (Request.Cookies["ileLogin"] != null)
                {
                    HttpCookie loginCookie = new HttpCookie("ileLogin");
                    loginCookie.Expires = DateTime.Now.AddDays(-1);
                    Response.Cookies.Add(loginCookie);
                }

                Response.Redirect("http://www.google.com/");
            }

            if (Request.Cookies["ileLogin"] != null)
            {
                int TabIndex = Convert.ToInt32(Server.HtmlEncode(Request.Cookies["ileLogin"]["LoginTabIndex"]).ToString());
                string storedUsername = Server.HtmlEncode(Request.Cookies["ileLogin"]["Username"]).ToString();

                TabContainerLogin.ActiveTabIndex = TabIndex;

                if (TabIndex == 0)
                {
                    Institut_Login.UserName = storedUsername;
                    Institut_Login.RememberMeSet = true;
                }
                else
                {
                    NonInstitut_Login.UserName = storedUsername;
                }
            }
        }
    }

    private void FocusRightControl()
    {
        HttpCookie cookie = Request.Cookies["ileLogin"];

        if (cookie != null)
        {
            System.Collections.Specialized.NameValueCollection values = cookie.Values;
            if (values[0].ToString() == "0")
            {
                TextBox userName = Institut_Login.FindControl("UserName") as TextBox;
                userName.Text = values[1].ToString();
                SetFocus(Institut_Login.FindControl("Password"));
            }
            else if (values[0].ToString() == "1")
            {
                TextBox userName = NonInstitut_Login.FindControl("Password") as TextBox;
                userName.Text = values[1].ToString();
                SetFocus(NonInstitut_Login.FindControl("Password"));
            }
        }
        else
        {
            TextBox userName = Institut_Login.FindControl("UserName") as TextBox;
            SetFocus(Institut_Login.FindControl("UserName"));
        }
    }

    private void SetFocus(Control control)
    {
        StringBuilder sb = new StringBuilder();

        sb.Append("\r\n<script language='JavaScript'>\r\n");
        sb.Append("<!--\r\n");
        sb.Append("function SetFocus()\r\n");
        sb.Append("{\r\n");
        sb.Append("\tdocument.");

        Control p = control.Parent;
        while (!(p is System.Web.UI.HtmlControls.HtmlForm)) p = p.Parent;

        sb.Append(p.ClientID);
        sb.Append("['");
        sb.Append(control.UniqueID);
        sb.Append("'].focus();\r\n");
        sb.Append("}\r\n");
        sb.Append("window.onload = SetFocus;\r\n");
        sb.Append("// -->\r\n");
        sb.Append("</script>");

        control.Page.RegisterClientScriptBlock("SetFocus", sb.ToString());
    }

    protected void Institut_Login_Authenticate(object sender, AuthenticateEventArgs e)
    {
        string Username = string.Empty;
        string Password = string.Empty;

        try
        {
            Username = Institut_Login.UserName.ToString();
            Password = Institut_Login.Password.ToString();
        }
        catch (Exception ex)
        {
            ModalPopupMessage.ShowModalPopup_Redirect("ILE Message", "We're sorry. An Error has occurred. Pleast try again.", 2, "Login.aspx");
            ileGlobal.RecordError("Login.aspx.cs:Institut_Login_Authenticate:010 Username Password get failed", ex, 4, Request.Browser);
            return;
        }
        
        
        int UserID = 0;

        // NEEDED?? Check if Username and Password is in right format.

        //if(true)

        bool authenticationResult = false;
        try
        {
            authenticationResult = Authentication(Username, Password);
        }
        catch (Exception ex)
        {
            ileGlobal.RecordError("Institut_Login_Authenticate:000", ex, "Authentication Function Result Failed", 4, Request.Browser);
        }

        if (authenticationResult)
        {
            int isUserInTable = -1;
            try
            {
                isUserInTable = usersLogic.IsUserInTable(Username);
            }
            catch (Exception ex)
            {
                ileGlobal.RecordError("Institut_Login_Authenticate:001:IsUserInTable Failed", ex, 4, Request.Browser);
            }
            switch (isUserInTable) // Check if User is already Registered in ILE Database
            {
                case 1: // When user exists in the table already
                    try
                    {
                        Users.UsersRow user = usersLogic.GetUserByUsername(Username);

                        if (user == null)
                        {
                            ModalPopupMessage.ShowModalPopup_Redirect("ILE Message", "We're sorry. An Error has occurred. Pleast try again.", 2, "Login.aspx");
                            return;
                        }
                        
                        if (user.IsEnabled == false)
                        {
                            e.Authenticated = false;
                            Institut_Login.FailureText = "Your account is deactivated.";
                            return;
                        }
                        else
                        {
                            UserID = user.UserID;

                            if (UserID == 0)
                            {
                                // NEED MORE WORK HERE
                                throw new NullReferenceException();
                            }

                            StoreUserInfoInSession(UserID, Username, user.AccountType);
                        }
                    }
                    catch (NullReferenceException ex)
                    {
                        ileGlobal.RecordError("Login.aspx.cs:Institut_Login_Authenticate:003", ex, 4, Request.Browser);
                        ModalPopupMessage.ShowModalPopup("Error", "Critical Error has occurred", 2);
                        return;
                    }
                    catch (Exception ex)
                    {
                        ileGlobal.RecordError("Login.aspx.cs:Institut_Login_Authenticate:004", ex, 4, Request.Browser);
                        ModalPopupMessage.ShowModalPopup("Error", "Critical Error has occurred", 2);
                        return;
                    }
                    break;
                case 0: // When user does not exist in the table

                    string FirstName = string.Empty;
                    string LastName = string.Empty;
                    string StudentIDNumber = string.Empty;
                    string Email = string.Empty;

                    // *** Fetch User information from School Server.
                    // This is how WSU did.
                    /* Psuedo code would be
                     * 
                     * 1. Access to the server you need to get user information.
                     * 2. Get user information
                     * 3. Put the information in the variabled declared right above this section.
                     * 4. If one certain element is not available,
                     *      Make it "Private"
                     *      
                     * 
                     i.g.
                    
                        try
                        {
                            Email = UserInfo["Email"].ToString();
                        }
                        catch
                        {
                            Email = "Private";
                        }
                    */

                    try
                    {

                        UserID = usersLogic.InsertUser(Username, "Student", FirstName, LastName, StudentIDNumber, Email, -1);
                    }
                    catch (Exception ex)
                    {
                        ileGlobal.RecordError("Login.aspx.cs:Institut_Login_Authenticate:005", ex, "Could Not Insert User to DB", 4, Request.Browser);
                        ModalPopupMessage.ShowModalPopup_Redirect("ILE Message", "We're sorry. An Error has occurred. Pleast try again.", 2, "Login.aspx");
                        return;
                    }

                    try
                    {
                        StoreUserInfoInSession(UserID, Username, "Student");
                    }
                    catch (Exception ex)
                    {
                        ileGlobal.RecordError("Login.aspx.cs:Institut_Login_Authenticate:006", ex, "Could Not Store Data into Session", 4, Request.Browser);
                        return;
                    }
                    break;
                case -1: // When Error Occurred
                    Institut_Login.FailureText = "There was an error while processing data, please try again.";
                    e.Authenticated = false;
                    ileGlobal.RecordError("Login.aspx.cs:Institut_Login_Authenticate:007", "Could Not Connect to DB", 4, Request.Browser);
                    return;
            }

            try
            {
                e.Authenticated = true;
                CreateAuthenticationTicket(Username);
            }
            catch (Exception ex)
            {
                ileGlobal.RecordError("Login.aspx.cs:Institut_Login_Authenticate:008", ex, "Could Not Create Authentication Ticket.", 4, Request.Browser);
                return;
            }
            
            try
            {
                // Record Login
                int Stats_LoginID = statsLogic.InsertStatsLogin(UserID, Request.UserHostAddress.ToString(), Request.Browser.Platform.ToString(), Request.Browser.Browser.ToString() + " " + Request.Browser.Version.ToString());
                //int Stats_LoginID = statsLogic.InsertStatsLogin(UserID, "TEST", "TEST", "TEST" + " " + "TEST");
                // Store StatsLoginID for Logging Logout time when user leaves ILE.
                HttpContext.Current.Session.Add("StatsLoginID", Stats_LoginID.ToString());
            }
            catch (Exception ex)
            {
                ileGlobal.RecordError("Login.aspx.cs:Institut_Login_Authenticate:002 Failed to Record Login Stats", ex, 3, Request.Browser);
                ModalPopupMessage.ShowModalPopup_Redirect("ILE Message", "Error has occurred while your logging in. Please try again.", 2, "Login.aspx");
                return;
            }

            // SET COOKIE for storing Login Information (IT does NOT include PASSWORD INFORMATION!!)
            if (Institut_Login.RememberMeSet == true)
            {
                HttpCookie loginCookie = new HttpCookie("ileLogin");
                loginCookie.Values["LoginTabIndex"] = "0";
                loginCookie.Values["Username"] = Username;
                loginCookie.Expires = DateTime.Now.AddMonths(1);
                Response.Cookies.Add(loginCookie);
            }
            else
            {
                HttpCookie loginCookie = new HttpCookie("ileLogin");
                loginCookie.Values["LoginTabIndex"] = "0";
                loginCookie.Values["Username"] = "";
                loginCookie.Expires = DateTime.Now.AddMinutes(-1);
                Response.Cookies.Add(loginCookie);
            }

            // Redirect users to MyClasses Page when they are from Help page
            if (Request.QueryString["ReturnUrl"].ToLower().Contains("help.aspx"))
            {
                Response.Redirect("MyClasses.aspx");
            }

            // Uncomment the line below if you want to redirect the users to MyClasses page all the time.
            //Response.Redirect("MyClasses.aspx");
        }
        else
        {
            if (HttpContext.Current.Session["AntiHacking"] == null)
            {
                HttpContext.Current.Session["AntiHacking"] = "1";
            }
            else if (Convert.ToInt32(HttpContext.Current.Session["AntiHacking"]) >= 4)
            {
                Institut_Login.FailureText = "Your login attempt failed, please again.<br />You will be locked out if you fail once more.";
                SetFocus(Institut_Login.FindControl("Password"));
            }
            else
            {
                Institut_Login.FailureText = "Your login attempt failed, please again.";
                SetFocus(Institut_Login.FindControl("Password"));
            }

            HttpContext.Current.Session["AntiHacking"] = (Convert.ToInt32(HttpContext.Current.Session["AntiHacking"].ToString()) + 1).ToString();

            e.Authenticated = false;
        }
    }

    protected void NonInstitut_Login_Authenticate(object sender, AuthenticateEventArgs e)
    {
        string Username = NonInstitut_Login.UserName.ToString();
        string Password = NonInstitut_Login.Password.ToString();
        bool RememberMeSet = NonInstitut_Login.RememberMeSet;

        if (usersLogic.AuthenticateNonInstitutUser(Username, Password)) // If Registered and Password is matching,
        {
            Users.UsersRow user = usersLogic.GetUserByUsername(Username);

            if (user == null)
            {
                ModalPopupMessage.ShowModalPopup_Redirect("ILE Message", "We're sorry. An Error has occurred. Pleast try again.", 2, "Login.aspx");
                return;
            }

            if (user.IsEnabled == false)
            {
                // *SteveMsg
                string _msg = "Your Account is Not Activated yet. Please Click <a href='ActivateAccount.aspx?Email=" + Username + "'>Here</a> and Activate Your Account.";
                ModalPopupMessage.ShowModalPopup("ILE Message", _msg, 2);
                e.Authenticated = false;
                return;
            }

            if (StoreUserInfoInSession(Convert.ToInt32(user.UserID), Username, user.AccountType))
            {
                e.Authenticated = true;
                CreateAuthenticationTicket(Username);

                try
                {
                    // Record Login
                    int Stats_LoginID = statsLogic.InsertStatsLogin(user.UserID, Request.UserHostAddress.ToString(), Environment.OSVersion.ToString(), Request.Browser.Browser.ToString() + " " + Request.Browser.Version.ToString());
                    // Store StatsLoginID for Logging Logout time when user leaves ILE.
                    HttpContext.Current.Session["StatsLoginID"] = Stats_LoginID.ToString();
                }
                catch (Exception ex)
                {
                    ileGlobal.RecordError("Login.aspx.cs:NonInstitut_Login_Authenticate:000 Failed to Record Login Stats", ex, 3, Request.Browser);
                }

                // SET COOKIE for storing Login Information (IT does NOT include PASSWORD INFORMATION!!)
                if (NonInstitut_Login.RememberMeSet == true)
                {
                    HttpCookie loginCookie = new HttpCookie("ileLogin");
                    loginCookie.Values["LoginTabIndex"] = "1";
                    loginCookie.Values["Username"] = Username;
                    loginCookie.Expires = DateTime.Now.AddMonths(1);
                    Response.Cookies.Add(loginCookie);
                }
                else
                {
                    HttpCookie loginCookie = new HttpCookie("ileLogin");
                    loginCookie.Values["LoginTabIndex"] = "1";
                    loginCookie.Values["Username"] = "";
                    loginCookie.Expires = DateTime.Now.AddMinutes(-1);
                    Response.Cookies.Add(loginCookie);
                }

                //Response.Redirect("MyClasses.aspx");
            }
            else
            {
                e.Authenticated = false;
                //Response.Redirect("MyClasses.aspx");
            }

        }
        else
        {
            TabContainerLogin.ActiveTabIndex = 1;

            if (HttpContext.Current.Session["AntiHacking"] == null)
            {
                HttpContext.Current.Session["AntiHacking"] = "1";
            }
            else if (Convert.ToInt32(HttpContext.Current.Session["AntiHacking"]) >= 4)
            {
                NonInstitut_Login.FailureText = "Your login attempt was not successful. Please try again.<br />You will be locked out if you fail once more.<br />Forgot your Password? <a href='PasswordRecovery.aspx'>Click Here</a>";
            }
            else
            {
                NonInstitut_Login.FailureText = "Your login attempt was not successful. Please try again.<br />Forgot your Password? <a href='PasswordRecovery.aspx'>Click Here</a>";
            }

            HttpContext.Current.Session["AntiHacking"] = (Convert.ToInt32(HttpContext.Current.Session["AntiHacking"].ToString()) + 1).ToString();

            e.Authenticated = false;
        }

    }

    protected void CreateAuthenticationTicket(string username)
    {
        try
        {
            bool isPersistent = false;
            string userData = "user";

            Institut_Login.FailureText = ""; // Do not display Failure Text
            
            // Create the ticket, and add the groups.
            FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1,
                username,
                DateTime.Now,
                DateTime.Now.AddMinutes(10),
                isPersistent,
                userData);

            // Encrypt the ticket.
            string encryptedTicket = FormsAuthentication.Encrypt(authTicket);

            // Create a cookie, and then add the encrypted ticket to the cookie as data.
            Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket));
        }
        catch (Exception ex)
        {
            ileGlobal.RecordError("Login.aspx.cs:CreateAuthenticationTicket:000 Failed to Create Authentication Ticket", ex, 3, Request.Browser);
        }
    }


    /// <summary>
    /// If NetworkID and Password are matching, return TRUE
    /// </summary>
    /// <param name="WSU_NetworkID"></param>
    /// <param name="Password"></param>
    /// <returns>TRUE for Authenticated, FALSE for NOT Authenticated.</returns>
    /// *** Create Authentication Function
    private bool Authentication(string Username, string Password)
    {
        // if the Username and Password matches, return TRUE. Otherwise, false.
        return false;
    }



    private bool StoreUserInfoInSession(int UserID, string Username, string AccountType)
    {
        try
        {
            if (UserID == 0)
            {
                ileGlobal.RecordError("Login.aspx.cs:StoreUserInfoInSession:001", "Passed UserID is ZERO", 3, Request.Browser);
                return false;
            }
            HttpContext.Current.Session.Add("UserID", UserID.ToString());
            HttpContext.Current.Session.Add("Username", Username);
            HttpContext.Current.Session.Add("AccountType", AccountType);
        }
        catch (Exception ex)
        {
            ileGlobal.RecordError("Login.aspx.cs:StoreUserInfoInSession:000 Failed to put user Info in Session", ex, 3, Request.Browser);
            return false;
        }
        return true;
    }
}
